# -*- coding:utf-8 -*-
"""
@文件 LoggingMiddleware.py
@Time : 2025/2/26
@Author: zjj
@Des: 日志中间件文件
@Email: 1065377805@qq.com

"""
import datetime
import json
import logging
import os
import time

from starlette.middleware.base import BaseHTTPMiddleware
from fastapi import FastAPI, Request, Response

LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO').upper()
logging.basicConfig(
    level=LOG_LEVEL,
    format='%(asctime)s - %(levelname)s - %(message)s'
)


class LoggingMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next) -> Response:
        start_time = time.perf_counter()
        response = await call_next(request)
        process_time = time.perf_counter() - start_time
        log_data = {
            "client_ip": request.client.host,
            "method": request.method,
            "path": request.url.path,
            "status_code": response.status_code,
            "process_time": f"{process_time:.4f}s",
            "timestamp": datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
        }

        # 根据环境变量决定是否打印详细的日志内容
        if LOG_LEVEL == 'DEBUG':
            log_data["headers"] = dict(request.headers)
            log_data["query_params"] = dict(request.query_params)

        logging.info(json.dumps(log_data))

        return response
